/* eslint-disable react/jsx-key */
import React, { useState, useRef } from 'react';
import AutoTable from '@/components/AutoTable';
import InitForm from '@/components/InitForm';
import { Modal, Button, Popconfirm, Image, message } from 'antd';
import { useRequest } from 'ahooks';
import { doFetch } from '@/utils/doFetch';
import { UserAddOutlined } from '@ant-design/icons';
import { role, area } from '@/services/api';
import { getPwdStrengthlength } from '@/components/StrengthPwd/strength';

let defaultFields = {
  name: {
    value: null,
    type: 'input',
    title: '用户名',
    name: ['name'],
    required: true,
  },
  real_name: {
    value: null,
    type: 'input',
    title: '真实姓名',
    name: ['real_name'],
    required: true,
  },
  sex: {
    value: null,
    type: 'radio',
    title: '性别',
    name: ['sex'],
    required: true,
    options: [
      {
        label: '男',
        value: '男',
      },
      {
        label: '女',
        value: '女',
      },
    ],
  },
  phone: {
    value: null,
    type: 'input',
    title: '手机号',
    name: ['phone'],
    required: true,
  },
  password: {
    value: null,
    type: 'password',
    title: '明文密码',
    name: ['password'],
    required: true,
  },
  email: {
    value: null,
    type: 'input',
    title: '邮箱',
    name: ['email'],
    required: true,
  },
  role_ids: {
    value: null,
    type: 'select',
    title: '角色',
    name: ['role_ids'],
    required: true,
    multiple: true,
    options: {
      database: role,
      params: {
        is_all: 1,
      },
    },
  },
};

let User = ({ route }) => {
  let columns = [
    {
      title: '用户名',
      dataIndex: 'name',
      key: 'name',
    },
    {
      title: '真实姓名',
      dataIndex: 'real_name',
      key: 'real_name',
    },
    {
      title: '性别',
      dataIndex: 'sex',
      key: 'sex',
      search: false,
    },
    {
      title: '手机号',
      dataIndex: 'phone',
      key: 'phone',
      search: false,
    },
    {
      title: '邮箱',
      dataIndex: 'email',
      key: 'email',
      search: false,
    },
    {
      title: '微信昵称',
      dataIndex: 'nick_name',
      key: 'nick_name',
      search: false,
    },
    {
      title: '微信头像',
      dataIndex: 'head_image',
      key: 'head_image',
      search: false,
      render: (dom, row) => (
        <Image
          src={row.head_image}
          width={20}
          height={20}
          onError={(e) => {
            e.target.onerror = null;
            e.target.src = require('@/assets/default.png');
          }}
        />
      ),
    },
    {
      title: '操作',
      valueType: 'option',
      width: 100,
      render: (text, record, _, action) => [
        <a
          style={{ color: '#1890ff' }}
          onClick={() => {
            cv(true);
            cf((fields) => {
              for (let i in fields) {
                fields[i].value = record[i];
                if (i == 'role_ids') {
                  fields[i].value = record.roles.map((it) => it.role_id);
                }
                if (i == 'password') {
                  fields[i].hides = true;
                }
              }
              return { ...fields };
            });
            ciftype({
              val: 'edit',
              title: '编辑用户',
              id: record.id,
            });
          }}
        >
          编辑
        </a>,
        <Popconfirm
          placement="bottom"
          title={'确认删除该用户？'}
          onConfirm={() => {
            run({ url: '/vehicle-api/user/' + record.id, params: {}, type: 'delete' });
          }}
          okText="删除"
          cancelText="取消"
        >
          <a style={{ color: '#f50' }}>删除</a>
        </Popconfirm>,
      ],
    },
  ],
    [visible, cv] = useState(false),
    [iftype, ciftype] = useState({}),
    [fields, cf] = useState(defaultFields);

  let actionRef = useRef(),
    ChildRef = null;
  function reload() {
    actionRef?.current?.reload();
    ChildRef?.onRefresh();
  }

  let { run, loading } = useRequest(doFetch, {
    debounceWait: 300, //防抖
    manual: true,
    formatResult: (res) => res,
    onSuccess: (result, params) => {
      reload();
      cv(false);
    },
  });

  // columns.map((it) => {
  //   obj[it.key] = it.title;

  // })
  // console.log(JSON.stringify(obj))

  return (
    <div style={{ width: '100%', height: '100%' }}>
      <Modal
        visible={visible}
        title={iftype.title}
        onCancel={() => {
          cv(false);
        }}
        footer={false}
        destroyOnClose={true}
      >
        <InitForm
          fields={fields}
          submitData={(values) => {
            if (values?.password && getPwdStrengthlength(values?.password) != 4) {
              message.warning("您的密码强度较弱，请按照提示规则设置密码！")
              return
            }
            if (iftype.val == 'add') {
              run({ url: '/vehicle-api/user', params: values });
            } else {
              run({ url: '/vehicle-api/user/' + iftype.id, params: values, type: 'PUT' });
            }
          }}
          onChange={(changedValues, allValues) => {
            //联动操作
          }}
          submitting={loading}
        />
      </Modal>
      <AutoTable
        pagetitle={route.name}
        pageextra={[
          <Button
            type="primary"
            icon={<UserAddOutlined />}
            onClick={() => {
              cf((fields) => {
                for (let i in fields) {
                  fields[i].value = i == 'role_ids' ? [] : null;
                  fields[i].hides = false;
                }
                return { ...fields };
              });
              cv(true);
              ciftype({
                title: '新增用户',
                val: 'add',
              });
            }}
          />,
        ]}
        actionRef={actionRef}
        onRef={(node) => (ChildRef = node)}
        path="/vehicle-api/user"
        rowClassName={(record, index) => {
          let className = index % 2 ? 'shallow_gray' : 'deep_gray';
          return className;
        }}
        columns={columns}
      />
    </div>
  );
};

export default User;
